import json
import threading

from django.db import connection

from app.decorator import jwt_auth
from app.service import app_api, payment
from app.service.member import get_member_by_username
from app.service.storage_card import get_storage_cards
from libs import payment_lib, common
from libs.common import success, error
from libs.db import DB
from libs.form import RawJsonForm


def storage_cards(request):
    arr = get_storage_cards()
    return success(arr)


@jwt_auth
def top_up(request, auth):
    try:
        form = RawJsonForm(request.body)
        username = form.get('username')
        db_mem = get_member_by_username(username, ['id'])
        db_mem_id = db_mem.get('id', 0)
        if not db_mem_id > 0:
            return error('会员信息不存在')
        card_id = form.get_int('card_id', 0)
        if card_id == 0:
            return error('无效的仓储卡类型')
        pay_mode = form.get_int('pay_mode')
        if pay_mode == 0:
            return error('无效的支付类型')
        num = form.get_int('num')
        if num <= 0:
            return error('无效的购买数量')

        order_sn = payment.gen_pay_order_sn(2)
        with connection.cursor() as cursor:
            cashier_id = str(auth.get('cashier_id'))
            db = DB('storage_card', conn=cursor)
            arr = [card_id]
            db_storage_card = db.one(['id', 'quota'], where='id=%s', binding_arr=arr)
            db_card_id = db_storage_card.get('id', 0)
            if db_card_id == 0:
                return error('仓储卡类型不存在')
            db_card_quota = db_storage_card.get('quota', 0)
            if db_card_quota <= 0:
                return error('无效的充值金额')
            if pay_mode == 100:  # 微信或支付宝
                pay_code = form.get_int('pay_code')

                pay_code_info = payment_lib.get_pay_code_type(pay_code)
                if type(pay_code_info) is dict:
                    third_party_pay_flag = pay_code_info.get('code')
                else:
                    return error('无效的第三方支付方式')

                if third_party_pay_flag == 1:
                    pay_mode = 2
                elif third_party_pay_flag == 2:
                    pay_mode = 3

                top_up_yuan = num * db_card_quota
                ip = common.get_ip(request)
                # 创建第三方充值支付订单
                rowid, err = payment.create_top_up_order(cursor, {
                    'cashier_id': cashier_id,
                    'order_sn': order_sn,
                    'pay_yuan': top_up_yuan,
                    'order_args': json.dumps({
                        'card_id': card_id,
                        'username': username,
                        'pay_mode': pay_mode,
                        'num': num,
                    }),
                    'ip': ip,
                })
                if not (err is None and rowid > 0):
                    return error('充值订单创建失败')

                th = threading.Thread(target=payment.process_top_up_payment, args=(cashier_id,
                                                                                   order_sn,
                                                                                   third_party_pay_flag,
                                                                                   pay_code,))
                th.start()
                return success(order_sn=order_sn)
            else:
                app_pay_mode_dict = {
                    1: 4,
                    10: 7,
                }
                if pay_mode not in app_pay_mode_dict:
                    return error('无效的支付方式')
                app_pay_mode = app_pay_mode_dict.get(pay_mode)
                err = app_api.app_top_up(cashier_id, order_sn, card_id, username, app_pay_mode, num)
                if err is None:
                    return success(order_sn=order_sn)
                else:
                    return error(err)
    except Exception as e:
        print(e)
        err = '充值异常'
    return error(err)
